package com.dwms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dwms.entity.QueryRequest;
import com.dwms.entity.Result;
import com.dwms.entity.api.request.ApiCommonRequest;
import com.dwms.entity.api.response.ApiResponse;
import com.dwms.entity.common.CommonMessage;
import com.dwms.entity.common.MqRequest;
import com.dwms.enums.MqGroup;
import com.dwms.enums.ResultCode;
import com.dwms.feign.MqFeignClient;
import com.dwms.service.GatewayService;
import com.dwms.utils.EmptyUtils;
import com.dwms.utils.IdWorker;
import com.github.xiaoymin.knife4j.annotations.Ignore;
import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author WH
 * @className: GatewayController
 * @description: 开放接口
 **/
@Ignore
@Slf4j
@Controller
@RequestMapping(value = "/hs/notify/gateway")
public class HsNotifyController {

    @Resource
    private MqFeignClient mqFeignClient;

    /**
     * 订单网关接口
     */
    @RequestMapping
    public void gateway(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            String data = request.getParameter("data");
            log.info("海关回执回调========" + data);
            Result result = sendMq(data);
            log.info("海关回执处理=====" + JSON.toJSONString(result));
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("true");
        }catch (Exception e) {
            log.error("海关回执异常", e);
        }
    }

    /**
     * 发送MQ消息
     * @param data
     * @return
     */
    private Result sendMq(String data) {
        if (EmptyUtils.isEmpty(data)) {
            return Result.failed(ResultCode.PARAM_IS_BLANK);
        }
        CommonMessage commonMessage = CommonMessage.common(IdWorker.getIdStr(), MqRequest.addJson(MqGroup.HS_NOTIFY, QueryRequest.build(data )));
        log.info("海关回执消息：{}", commonMessage);
        Result result = mqFeignClient.sendMsg(commonMessage);
        if (result.isFailed()) {
            return Result.failed("海关回执发送失败,请联系客服");
        }
        return Result.success();
    }
}
